/**
 * @filename:PickController Sep 23, 2024
 * @project Wonder Vue Admin Api  1.1.0
 * Copyright(c) 2020 Wonder Co. Ltd. 
 * All right reserved. 
 */
package com.wonder.app.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.vtuzx.core.VtuzxException;
import com.wonder.admin.domain.SysAdmin;
import com.wonder.admin.service.SysAdminService;
import com.wonder.app.domain.PickDetail;
import com.wonder.app.domain.PrdPick;
import com.wonder.app.request.PickDetailRequest;
import com.wonder.app.request.PrdPickRequest;
import com.wonder.app.service.BdPdaService;
import com.wonder.app.service.PrdPickService;
import com.wonder.framework.authorization.CheckAdminToken;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wonder.common.common.AjaxMap;
import com.wonder.common.common.AjaxResult;
import com.wonder.common.common.CommonPage;
import com.wonder.common.utils.MessageUtils;
import com.wonder.common.utils.StringUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;

import javax.servlet.http.HttpServletRequest;

/**
 *
 * <p>说明： 生产领料API接口层</P>
 * @version: 1.1.0
 * @author: Wonder
 * @time    Sep 23, 2024
 *
 */
@Api(tags = "生产领料")
@RestController
@RequestMapping("/app/Pick")
public class PrdPickController {

    @Autowired
    private PrdPickService prdPickService;

    @Autowired
    private CheckAdminToken checkAdminToken;

    @Autowired
    private SysAdminService adminService;


    @Autowired
    private BdPdaService bdPdaService;

    private Map<Long,Long> lastRequestTimeMap = new ConcurrentHashMap<>();

    @ApiOperation(value = "生产领料列表")
    @RequestMapping(value = "/index", method = RequestMethod.POST)
    public Map<String,Object> index(@RequestBody PrdPickRequest prdPickRequest) {
        Page<PrdPick> page = new Page<PrdPick>(prdPickRequest.getPage(), prdPickRequest.getLimit());
        IPage<PrdPick> list = prdPickService.selectList(prdPickRequest, page);

        Map<String,Object> retMap=new HashMap<>();
        retMap.put("data",CommonPage.restPage(list));


        return AjaxMap.success(retMap);
    }

    /**
     * @explain 修改排序开关
     * @param   entity
     * @return  Boolean
     * @author  Wonder
     */
    @PostMapping("/updateExt")
    @ApiOperation(value = "修改排序开关", notes = "作者：Wonder")
    public AjaxResult<PrdPick> updateExt(@RequestBody PrdPick entity){
        if (null!=entity) {
            boolean rsg = prdPickService.updateById(entity);
            if (rsg) {
                return AjaxResult.success("system.updateSuccess");
            }else {
                return AjaxResult.failed("system.updateFailed");
            }
        }else {
            return AjaxResult.failed("system.parameterError");
        }
    }

    /**
     * @explain 添加
     * @param   entity
     * @return  Boolean
     * @author  Wonder
     */
    @PostMapping("/add")
    @ApiOperation(value = "添加", notes = "作者：Wonder")
    public AjaxResult<PrdPick> add(@RequestBody PrdPick entity){

        if (null!=entity) {

            String validate=prdPickService.validate(entity,"new");
            if(StringUtils.hasText(validate))
                return AjaxResult.failed(validate);
            boolean rsg = prdPickService.save(entity);
            if (rsg) {
                return AjaxResult.success("system.insertSuccess");
            }else {
                return AjaxResult.failed("system.insertFailed");
            }
        }else {
            return AjaxResult.failed("system.parameterError");
        }
    }

    /**
     * @explain 查询对象  <swagger GET请求>
     * @param   map 对象参数：id
     * @return  JsonResult
     * @author  Wonder
     */
    @PostMapping("/getUpdateInfo")
    @ApiOperation(value = "获取生产领料对象", notes = "作者：Wonder")
    public AjaxResult<PrdPick> getUpdateInfo(@RequestBody Map<String,Object> map){
        if(map==null) return AjaxResult.failed("system.parameterError");
        Long Id=Long.parseLong(map.get("Id").toString());
        PrdPick pick=prdPickService.getById(Id);

        if (null!=pick ) {
            return AjaxResult.success(pick);
        }else {
            return AjaxResult.failed("system.parameterError");
        }

    }

    /**
     * @explain 修改
     * @param   entity
     * @return  Boolean
     * @author  Wonder
     */
    @PostMapping("/update")
    @ApiOperation(value = "修改", notes = "作者：Wonder")
    public AjaxResult<PrdPick> update(@RequestBody PrdPick entity){
        if (null!=entity) {
            String validate=prdPickService.validate(entity,"update");
            if(StringUtils.hasText(validate))
                return AjaxResult.failed(validate);
            boolean rsg = prdPickService.updateById(entity);
            if (rsg) {
                return AjaxResult.success("system.updateSuccess");
            }else {
                return AjaxResult.failed("system.updateFailed");
            }
        }else {
            return AjaxResult.failed("system.parameterError");
        }
    }

    /**
     * 传金蝶领料单
     * @param map
     * @return
     */
//    @ApiOperation(value = "传金蝶领料单")
//    @ResponseBody
//    @PostMapping(value = "/upload_kingdee_pick_order")
//    public AjaxResult<?> uploadKingdeePickOrder(HttpServletRequest request, @RequestBody Map<String,Object> map) throws Exception{
//        String billNo = map.get("billNo").toString();
//        String pickNo = map.get("pickNo").toString();
//        prdPickService.uploadKingdeePickOrder(billNo,pickNo);
//        return null;
//    }

//    /**
//     * 删除领料信息
//     * @param map
//     * @return
//     */
//    @ApiOperation(value = "删除领料信息")
//    @ResponseBody
//    @PostMapping(value = "/delete_pick_material")
//    public AjaxResult<?> deleteMaterial(HttpServletRequest request, @RequestBody Map<String,Object> map) throws Exception{
//        String token = checkAdminToken.getTokenFormRequest(request);
//        SysAdmin user = adminService.getAdminByToken(token);
//        Long userId = user.getUser_id();
//        String userName = user.getName();
//        Boolean res = prdPickService.deleteMaterial(userName,map);
//        if (res){
//            return AjaxResult.success(res);
//        } else {
//            return AjaxResult.failed();
//        }
//    }

    /**
     * @explain 删除
     * @param   map 对象参数：id
     * @return  JsonResult
     * @author  Wonder
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除", notes = "作者：Wonder")
    public AjaxResult<PrdPick> delete(@RequestBody Map<String,Object> map){
        if(map==null)return AjaxResult.failed("system.parameterError");
        String ids=map.get("Id").toString();
        ids=StringUtils.remove(ids, '[');
        ids=StringUtils.remove(ids, ']');
        String[] deleteIds=StringUtils.split(ids, ',');
        List<Long> idList=new ArrayList<>();
        for(int i=0;i<deleteIds.length;i++)
        {
            idList.add( Long.parseLong(deleteIds[i].trim()));//整数数组
        }

        boolean rsg = prdPickService.removeBatchByIds(idList);
        if (rsg) {
            return AjaxResult.success("system.deleteSuccess");
        }else {
            return AjaxResult.failed("system.deleteFailed");
        }

    }

    /**
     * @explain 查看对象明细
     * @param   map 对象参数：id
     * @return  JsonResult
     * @author  Wonder
     */
    @ApiOperation(value = "查询prdpick明细")
    @ResponseBody
    @PostMapping(value = "/prdpickdetail")

    public AjaxResult<Map<String,Object>> getPrdPickDetail(HttpServletRequest request, @RequestBody Map<String,Object> map) throws Exception{
        if (null == map){
            return AjaxResult.failed("system.parameterError");
        }
        Map<String,Object> data = prdPickService.getPrdPickDetail(map);
        if (null != data){
            return AjaxResult.success(data);
        } else {
            return AjaxResult.failed();
        }
    }


    /**
     * 创建领料单
     * @param map
     * @return
     */
    @ApiOperation(value = "创建领料单")
    @ResponseBody
    @PostMapping(value = "/create_pick_bill")
    public AjaxResult<Boolean> createPickBill(HttpServletRequest request, @RequestBody Map<String,Object> map) throws Exception{
        String token = checkAdminToken.getTokenFormRequest(request);
        SysAdmin user = adminService.getAdminByToken(token);
        Long userId = user.getUser_id();
        String userName = user.getName();
        //从map中查找上次请求的时间戳
        Long lastRequestTime = lastRequestTimeMap.get(userId);
        //如果为空或者上次请求的时间戳与当前时间做差大于5s，则视为新请求，否则重复请求。
        if (lastRequestTime == null || System.currentTimeMillis() - lastRequestTime > 20000) {
            lastRequestTimeMap.put(userId, System.currentTimeMillis());
            // 处理请求
            Boolean res = prdPickService.createPickBill(userId,userName,map);
            if (res){
                return AjaxResult.success(res);
            } else {
                return AjaxResult.failed();
            }
        } else {
            // 重复请求
            throw new Exception("正在领料，请不要重复点击");
        }


    }


    /**
     * 创建领料单临时数据
     * @param map
     * @return
     */
    @ApiOperation(value = "创建领料单临时数据")
    @ResponseBody
    @PostMapping(value = "/create_pick_detail_temp")
    public AjaxResult<?> createPickDetailTemp(HttpServletRequest request, @RequestBody Map<String,Object> map) throws Exception{
        String token = checkAdminToken.getTokenFormRequest(request);
        SysAdmin user = adminService.getAdminByToken(token);
        Long userId = user.getUser_id();
        String userName = user.getName();

        // 处理请求
        Boolean res = prdPickService.createPickDetailTemp(userName,map);

        return AjaxResult.success(res);

    }


    /**
     * 删除领料中的临时数据
     * @param map
     * @return
     */
    @ApiOperation(value = "删除领料中的临时数据")
    @ResponseBody
    @PostMapping(value = "/delete_pick_detail_temp")
    public AjaxResult<?> deletePickDetailTemp(HttpServletRequest request, @RequestBody Map<String,Object> map) throws Exception{
        String token = checkAdminToken.getTokenFormRequest(request);
        SysAdmin user = adminService.getAdminByToken(token);
        Long userId = user.getUser_id();
        String userName = user.getName();

        // 处理请求
        Boolean res = prdPickService.deletePickDetailTemp(userName,map);

        return AjaxResult.success(res);

    }


    /**
     * 机加车间还没有打印的托盘
     * @param map
     * @return
     */
    @ApiOperation(value = "机加车间还没有打印的托盘")
    @RequestMapping(value = "/get_jijia_tray", method = RequestMethod.POST)
    public AjaxResult<Map<String,Object>> getJijiaTray(@RequestBody Map<String,Object> map) throws Exception {

        Map<String,Object> data = prdPickService.getJijiaTray(map);
        if (null != data){
            return AjaxResult.success(data);
        } else {
            return AjaxResult.failed();
        }
    }

    /**
     * 修改机加车间托盘打印的状态
     * @param map
     * @return
     */
    @ApiOperation(value = "修改机加车间托盘打印的状态")
    @RequestMapping(value = "/update_jijia_tray", method = RequestMethod.POST)
    public AjaxResult<?> updateJijiaTray(@RequestBody Map<String,Object> map) throws Exception {

        Boolean res = prdPickService.updateJijiaTray(map);
        if (res){
            return AjaxResult.success(res);
        } else {
            return AjaxResult.failed();
        }
    }

    /**
     * 修改机加车间托盘打印的状态为未打印
     * @param map
     * @return
     */
    @ApiOperation(value = "修改机加车间托盘打印的状态为未打印")
    @RequestMapping(value = "/update_print", method = RequestMethod.POST)
    public AjaxResult<?> updatePrint(HttpServletRequest request,@RequestBody Map<String,Object> map) throws Exception {
        String token = checkAdminToken.getTokenFormRequest(request);
        SysAdmin user = adminService.getAdminByToken(token);
        Long userId = user.getUser_id();
        String userName = user.getName();
        Boolean res = prdPickService.updatePrint(userName,map);
        if (res){
            return AjaxResult.success(res);
        } else {
            return AjaxResult.failed();
        }
    }

    /**
     * 根据pdauuid获取绑定的蓝牙地址
     * @param map
     * @return
     */
    @ApiOperation(value = "根据pdauuid获取绑定的蓝牙地址")
    @RequestMapping(value = "/get_mac_by_uuid", method = RequestMethod.POST)
    public AjaxResult<?> getMacByUuid(HttpServletRequest request,@RequestBody Map<String,Object> map) throws Exception {
        String token = checkAdminToken.getTokenFormRequest(request);
        SysAdmin user = adminService.getAdminByToken(token);
        Long userId = user.getUser_id();
        String userName = user.getName();
        Map<String,Object> res = bdPdaService.getMacByUuid(userId,map);

        return AjaxResult.success(res);

    }

    /**
     * 绑定uuid和打印机地址
     * @param map
     * @return
     */
    @ApiOperation(value = "根据pdauuid获取绑定的蓝牙地址")
    @RequestMapping(value = "/banding_mac_by_uuid", method = RequestMethod.POST)
    public AjaxResult<?> bandingMacByUuid(HttpServletRequest request,@RequestBody Map<String,Object> map) throws Exception {
        String token = checkAdminToken.getTokenFormRequest(request);
        SysAdmin user = adminService.getAdminByToken(token);
        Long userId = user.getUser_id();
        String userName = user.getName();
        Boolean res = bdPdaService.bandingMacByUuid(userId,map,userName);

        return AjaxResult.success(res);

    }


    @ApiOperation(value = "领料详情列表")
    @RequestMapping(value = "/detail_index", method = RequestMethod.POST)
    public Map<String,Object> detailIndex(@RequestBody PickDetailRequest detailRequest) throws Exception{
        Page<PickDetail> page = new Page<PickDetail>(detailRequest.getPage(), detailRequest.getLimit());
        IPage<PickDetail> list = prdPickService.selectDetailList(detailRequest, page);

        Map<String,Object> retMap=new HashMap<>();
        retMap.put("data",CommonPage.restPage(list));


        return AjaxMap.success(retMap);
    }
}